package com.fgba.express.security;



import com.fgba.express.util.NullChecker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用户名和密码登陆验证的过滤器
 *
 * @author fgba
 */
@Slf4j
public class CustomAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    private boolean postOnly = true;
    public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "username";
    public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "password";

    private String usernameParameter = SPRING_SECURITY_FORM_USERNAME_KEY;
    private String passwordParameter = SPRING_SECURITY_FORM_PASSWORD_KEY;

    public CustomAuthenticationFilter() {
        //父类中定义了拦截的请求URL，/login的post请求，直接使用这个配置，也可以自己重写
        super("/login");
    }



    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        if (postOnly && !HttpMethod.POST.name().equalsIgnoreCase(request.getMethod())) {
            throw new AuthenticationServiceException(
                    "不支持身份验证方法: " + request.getMethod());
        }
        String username = obtainUsername(request);
        String password = obtainPassword(request);

        if (NullChecker.isNullOrEmpty(username)) {
            username = "";
        }

        if (NullChecker.isNullOrEmpty(password)) {
            password = "";
        }

        username = username.trim();
        CustomAuthenticationToken authRequest = new CustomAuthenticationToken(username, password);

        setDetails(request, authRequest);

        return this.getAuthenticationManager().authenticate(authRequest);
    }
    protected String obtainPassword(HttpServletRequest request) {
        String password =request.getParameter(passwordParameter);
        return NullChecker.isNullOrEmpty(password) ? "" : password;
    }
    protected String obtainUsername(HttpServletRequest request) {
        String username =request.getParameter(usernameParameter);
        return NullChecker.isNullOrEmpty(username) ? "" : username;
    }

    protected void setDetails(HttpServletRequest request,
                              UsernamePasswordAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }
}
